import django
from django import http
from django import shortcuts

from google.appengine.api import images

from blog.models import *
from blog.helper import *
from blog.sql import *
from blog.sessions import *
from conf.settings import *


def list(request):
    params = {}
    items = VCate.all()
    params['Title'] = 'List Cate'
    params['items'] = items
    return respond(request, None, 'vcate_list', params)

def delete(request, idItem):
    member = Permission(1)
    item = None
    if idItem:
        item = VCate.get_by_id(int(idItem))
        if item is None:
            return http.HttpResponseNotFound('No Item')
        else:
            if item.member.user != member.user:
                return respond(request, None, 'message_box', {"message":"No Permission."})
  
    item.delete()
    return http.HttpResponseRedirect('/vcate')

def add(request):
    return edit(request, None)

def edit(request, idItem):
    member = Permission(1)
    params = {}
    params['Title'] = 'Add/Edit Cate'
    
    item = None
    if idItem:
        item = VCate.get_by_id(int(idItem))
        if item is None:
            return http.HttpResponseNotFound('No Item')
        else:
            if item.member.user != member.user:
                return respond(request, None, 'message_box', {"message":"No Permission."})
    # Cate Option
    optionCate = ListOptionCate(0,'==',None,True)
    params['optionCate'] = optionCate
    
    params['item'] = item
  
    if not request.POST:
        return respond(request, None, 'vcate_edit', params)
  
    if item is None:
        item = VCate()
    try:            
        item.title      = unicode(SafePost('title', '', request), 'utf-8')
        item.status     = int(SafePost('status', 0, request))
        item.parent_id  = int(SafePost('parent_id', 0, request))
        item.member     = member
        
    except db.Error, err:
        params['err'] = err
        params['item'] = item
        return respond(request, None, 'vcate_edit', params)
  
    item.put()

    return http.HttpResponseRedirect('/vcate')

idOption = 0


